/* cache.js */

// in case localStorage isn't available
var lexiconCache = {};

function hasLocalStorage() {
	return !!window.localStorage;
}

function getCached(uid) {
	if (hasLocalStorage()) {
		var cached = localStorage.getItem(uid);
		if (!!cached) {
			return JSON.parse(cached);
		} else {
			return undefined;
		}
	} else {
		return lexiconCache[uid];
	}
}

function updateCached(dat) {
	if (hasLocalStorage()) {
		localStorage.setItem(dat.uid, JSON.stringify(dat));
	} else {
		lexiconCache[dat.uid] = dat;
	}
}

function removeCached(dat) {
	if (hasLocalStorage()) {
		localStorage.removeItem(dat.uid);
	} else {
		delete lexiconCache[dat.uid];
	}
}

/* ********************************** */

function requestUpdates(uid, last) {
	$.post("updates.json", {"uid": uid, "modified": last}, requestUpdates);
}

function receiveUpdates(dat) {
	// check whether received object (as anticipated from updates.json)
	if (!dat || typeof dat != "object") return;

	// assume it's well-formed
	if ("current" in dat) {
		// item in cache is latest
		// TODO clear any "requesting updates" status on this item, etc.
	} else if ("remove" in dat) {
		// server does not retain the item
		removeCached(dat);
		showItemRemoved(dat.uid);
	} else if ("modified" in dat) {
		// server sent an updated item
		updateCached(dat);
		showItem(dat);
	}
}
